/**
 * 
 */
package com.hcmu.view.MainHome;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import vanhoc.android.utils.AlertDialogManager;
import vanhoc.android.utils.ResourceUtils;

import com.hcmu.R;
import com.hcmu.common.SpinnerSetting;
import com.hcmu.dto.CategoryDTO;
import com.hcmu.dto.DatabaseHelper;
import com.hcmu.model.StoryDetailModel;
import com.hcmu.view.common.SettingFontSize;
import com.hcmu.view.custome.CategoryAdapter;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.Action;
import com.markupartist.android.widget.ActionBar.IntentAction;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.Element;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Html;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * @author SEVEN
 *
 */
public class ViewStoryDetailOnline extends Activity {
	View app;
	ActionBar actionBar;
	String storyTitle;
	Boolean isDownload = false;
	Boolean isShareFacebook = false;
	Spinner spinnerSetting;
	TextView txtContent;
	String url;
	String storyContent = "";
	Dialog categoriesDialog;
	DatabaseHelper db = new DatabaseHelper(this);
	SettingFontSize settingFont;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		LayoutInflater lf = LayoutInflater.from(this);
		app = lf.inflate(R.layout.layout_detail_story_online,  null);
		setContentView(app);

		getIntentData();
		
		actionBar = (ActionBar) app.findViewById(R.id.actionbar);
		actionBar.setHomeAction(new DownloadStoryAction(this, null, R.drawable.download_32_icon));
		actionBar.setTitle(storyTitle);
		
	    SharedPreferences sp = getPreferences(MODE_PRIVATE);
	    settingFont = new SettingFontSize(this, sp);
	    	
		txtContent = (TextView) app.findViewById(R.id.txtContent);
		new LoadContent().execute();
		viewContentFormat();
		 
		final View[] children = new View[] { app };
	}

	
	
	private void viewContentFormat() {
		txtContent.setTextSize(settingFont.getTextSize());
	}


	//Getting story data via intent
	private void getIntentData() {
		Intent it = getIntent();
		storyTitle = it.getExtras().getString("title");
		url = it.getStringExtra("page_url");
	}

	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_online_detail, menu);
        return true;
    }
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			settingFont.show(txtContent);
			return true;
		case R.id.menu_readOffline:
			startActivity(new Intent(ViewStoryDetailOnline.this, OfflineMainView.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	
	
	private void showSpinnerSetting() {
		LayoutInflater lf = LayoutInflater.from(this);
		View view = lf.inflate(R.layout.simple_spinner, null);
		
		spinnerSetting = (Spinner) view.findViewById(R.id.spinnerDefault);
		
		final String[] items = getResources().getStringArray(R.array.setting_font_text);
				
		//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
		
		ArrayAdapter adapter = new ArrayAdapter(
									this,
									android.R.layout.simple_spinner_item, 
									items);
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spinnerSetting.setAdapter(adapter);
		
	}

	/**
	 * Handle share up facebook action 
	 * @author SEVEN
	 *
	 */
	private  class ShareFacebookAction extends AbstractAction {
	    private Context mContext;
	    private Intent mIntent;
	
	    public ShareFacebookAction(Context context, Intent intent, int drawable) {
	        super(drawable);
	        mContext = context;
	        mIntent = intent;
	    }
	
	    @Override
	    public void performAction(View view) {
	    	Toast.makeText(getApplicationContext(), "Share facebook", Toast.LENGTH_LONG).show();
	    }
	}
	
	
	
	/**
	 * Handle share up facebook action 
	 * @author SEVEN
	 *
	 */
	private  class DownloadStoryAction extends AbstractAction {
	    private Context mContext;
	    private Intent mIntent;
	
	    public DownloadStoryAction(Context context, Intent intent, int drawable) {
	        super(drawable);
	        mContext = context;
	        mIntent = intent;
	    }
	
	    @Override
	    public void performAction(View view) {
			//startActivity(new Intent(ViewStoryDetailOnline.this, MainHome.class));
	    	downloadStory();
	    }
	}
	
	
	private ArrayList<CategoryDTO> getAllCategories() {
		ArrayList<CategoryDTO> categories = new ArrayList<CategoryDTO>();
		
		db.openToRead();
		Cursor cursor = db.getAllCategory();
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			for (int i = 0; i < cursor.getCount(); i++) {
				CategoryDTO dto = new CategoryDTO();
				dto.setId(Integer.parseInt(cursor.getString(0)));
				dto.setTitle(cursor.getString(1).toString());
				categories.add(dto);
				
				cursor.moveToNext();
			}
		}
		db.close();
		
		return categories;
	}
	
	
	ArrayList<CategoryDTO> categoriesList;
	public void downloadStory() {
		categoriesDialog = new Dialog(this, 0);
		categoriesDialog.setTitle(getResources().getString(R.string.download_client));
		categoriesDialog.setContentView(R.layout.listview);
		
		//get listview
		ListView categoryListView = (ListView) categoriesDialog.findViewById(R.id.listView);
		
		//get data to put listview
		categoriesList = getAllCategories();
		
		//item : add new category
		categoriesList.add(new CategoryDTO(0, getResources().getString(R.string.ADD_NEW)));
		
		CategoryAdapter adapter = new CategoryAdapter(ViewStoryDetailOnline.this, R.layout.simple_text, categoriesList);
		
		categoryListView.setAdapter(adapter);
		
		categoryListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
				int catId = categoriesList.get(position).getId();
				
				if (catId == 0) {//add new category
					createNewCategory();
					categoriesDialog.dismiss();
				}else{ //them truyen vao 1 cate co san
					db.openToWrite();
					db.insertStory(catId, storyTitle, storyContent, false, 1, 0, 0);
					db.close();
					
					categoriesDialog.dismiss();
					Toast.makeText(getApplicationContext(), R.string.SUCCESSFULLY, Toast.LENGTH_LONG).show();
				}
			}
		});
		
		categoriesDialog.show();
	}
	
	protected void createNewCategory() {
		final Dialog dialog = new Dialog(ViewStoryDetailOnline.this, 0);
		dialog.setTitle(getResources().getString(R.string.ADD_NEW));
		dialog.setContentView(R.layout.layout_quick_add_new_category);
		dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		dialog.show();
		
		final EditText txtTitle = (EditText) dialog.findViewById(R.id.txtTitle);
		Button btnSave = (Button) dialog.findViewById(R.id.btnSave);
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
		
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String catTitle = txtTitle.getText().toString();
				
				if (catTitle.equals(null) || catTitle.equals("")) {
					AlertDialogManager.showAlertDialog(ViewStoryDetailOnline.this, getResources().getString(R.string.ERROR), getResources().getString(R.string.PLEASE_ENTER_TITLE), false);
				}else{
					db.openToWrite();
					int newCatId = (int) db.insertCategory(catTitle);
					db.insertStory(newCatId, storyTitle, storyContent, false, 1, 0, 0);
					db.close();
					dialog.dismiss();
					Toast.makeText(getApplicationContext(), R.string.SUCCESSFULLY, Toast.LENGTH_LONG).show();
				}
			}
		});
		
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}

	
	
	public class LoadContent extends AsyncTask<Void, Void, Void>{
		Document doc;
		ProgressDialog pgDialog;
		
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			
			pgDialog = ProgressDialog.show(ViewStoryDetailOnline.this, "", "Loading...");
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			 try {
		 			doc = (Document) Jsoup.connect(url).get();
		 			org.jsoup.nodes.Element div = doc.select("div.article-content").first();
		 			
		 			Elements tags = div.getElementsByTag("p");
		 			for (org.jsoup.nodes.Element el : tags) {
		 				if (!el.equals("") || !el.equals(null)) {
		 					storyContent += "<p>" + el.html() + "</p>";
						}
					}
		 		 } catch (IOException e) {
		 			// TODO Auto-generated catch block
		 			e.printStackTrace();
		 		 }
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			if (pgDialog.isShowing()) {
				pgDialog.dismiss();
			}
			
			String[] content = storyContent.split("null");
			txtContent.setText(Html.fromHtml(content[content.length-1]));
			//txtContent.setText(Html.fromHtml(storyContent));
		}
	}

	
}

